<?php
namespace Weibo\Controller;
use Weibo\Controller\WeibobaseController;
// use Common\Controller\HomebaseController;

/**
 * 搜索控制器
 * @author Baiyu	2016-12-23
 */
class SearchController extends WeibobaseController {
/*warning--请勿动下面代码，我都不知道我写的什么！！哼哼*/


	/**
	 * 搜索
	 * @author	haofei	2016-12-23
	 * @param	string	$keyword		搜索内容
	 * @param	string	$type			搜索类型 all全部|weibo微博|user人
	 */
	public function index($keyword = '', $type = 'all'){
		/***step1 将关键字截取成数组***/
		$type = I("type");
		$keyword = I("keyword");

//		 $type = 'user';
//		 $keyword = '子 羿';

		!$type && ($type = 'all');
		$keyword = str_replace(' ',' ',$keyword); //将连续空格替换成为单个空格
		$keyword = explode(" ",$keyword);
		$keyword = array_filter($keyword); //删除空字符元素
		$keyword = array_values($keyword);
		$keyword_num = sizeof($keyword); //获取到关键词的元素个数



		/*** step2 模糊查询 weibo weibo_user 两表***/
		$weiboModel = D("Weibo/Weibo"); //微博表
		$weiboUserModel = D("Weibo/WeiboUser"); //微博用户表
		// $userModel = D("Weibo/Users"); //用户表
		$UserRelationModel = D("Weibo/WeiboUserRelation");//用户关系表
		$SearchCacheModel = D("Weibo/WeiboSearchCache"); //用户缓存表
		/*** step3 匹配查询类型***/
		// 判断$type 类型 对应查询
		switch ($type) {
			case 'all':
				/*** step3-1 将关键词进行Like模糊查询***/
				for ($i=0; $i < $keyword_num; $i++) {
					//查询微博内容
					$where_Weibo['content'] = array('like','%'.$keyword[$i].'%');
					$weiboCon = $weiboModel->where($where_Weibo)->select();
					//查询微博用户
					$where_WeiboUser['nickname'] = array('like','%'.$keyword[$i].'%');
					$weiboUserCon = $weiboUserModel->where($where_WeiboUser)->select();
					//将查询的结果放入数组中存放
					$weiboCon && $weiboArr[] = array(
						'OBkeyword' => $keyword[$i],
						'ResultSet' => $weiboCon,
					);
					$weiboUserCon && $weiboUserArr[] = array(
						'OBkeyword' => $keyword[$i],
						'ResultSet' => $weiboUserCon,
					);
					/*** step3-1-1 将搜索关键字存入搜索记录表中 WeiboSearchStat***/
					$SearchStatModel = D("Webo/WeiboSearchStat");
					$data['keyword'] = $keyword[$i];
					$data['create_time'] = time();
					$Stat_ruselt = $SearchStatModel->add($data);
				}
				if (!$weiboArr && !$weiboUserArr) { //都没有搜索到数据
					$assign['status'] = '0'; //没有数据的时候返回状态0
					 $this->output($assign);
				} else if ($weiboArr[0] || $weiboUserArr[0]) { //其中一种类型有数据的时候
					/*** step3-2 去除数组中的空元素***/
					$weiboArr = array_filter($weiboArr);
					$weiboUserArr = array_filter($weiboUserArr);
					/*** step3-3 去除数组中重复数据且不改变键值 ***/
					//声明一个数组
					$NewWeibo_arr = array();
					$NewWeiboUser_arr = array();
					//微博类型
					//$NewWeibo_arr 用于添加搜索缓存结果集
					foreach ($weiboArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibo';
							$v['OBkeyword'] = $value['OBkeyword'];
							$NewWeibo_arr[] = $v;
						}
					}
					//$NewWeibo_array 用于返回界面搜索结果
					foreach ($weiboArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibo';
							$NewWeibo_array[] = $v;
						}
					}
					//使用array_unique_fb方法去除数组中重复数据且不改变键值
					$NewWeibo_arr = array_unique_fb($NewWeibo_arr); //用于添加搜索缓存结果集
					$NewWeibo_array = array_unique_fb($NewWeibo_array); //用于返回界面结果集
					//微博用户类型
					//$NewWeiboUser_arr 用于添加搜索缓存结果集
					foreach ($weiboUserArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibouser';
							$NewWeiboUser_arr[] = $v;
						}
					}
					//NewWeiboUser_array 用于返回界面搜索结果
					foreach ($weiboUserArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibo';
							$NewWeiboUser_array[] = $v;
						}
					}
					//使用array_unique_fb方法去除数组中重复数据且不改变键值
					$NewWeiboUser_arr = array_unique_fb($NewWeiboUser_arr); //用于添加搜索缓存结果集
					$NewWeiboUser_array = array_unique_fb($NewWeiboUser_array); //用于返回界面结果集
					/*** step3-4 将关键之搜索到的数据集插入到缓存表中 WeiboSearchCache***/
					/***step3-4-1 将数组重新按关键字分组***/
					//将搜索关键词对应结果集序列化
					foreach ($NewWeibo_arr as $key => $value) {
						$result_All_weibo[$value['OBkeyword']][] = serialize($value);
					}
					foreach ($NewWeiboUser_arr as $key => $value) {
						$result_All_weiboUser[$value['OBkeyword']][] = serialize($value);
					}
					//微博类型
					foreach ($NewWeibo_arr as $key => &$value) {
						$value = serialize($value);
						$data['keyword'] = $key;
						$data['data'] = $value;
						$data['type'] = '1'; //1微博 2微博用户
						$data['update_time'] = time();
						// dump($data);
						$Cache_result = $SearchCacheModel->add($data);
					}
					//微博用户类型
					foreach ($NewWeiboUser_arr as $key => &$value) {
						$value = serialize($value);
						$data['keyword'] = $key;
						$data['data'] = $value;
						$data['type'] = '2'; //1微博 2微博用户
						$data['update_time'] = time();
						// dump($data);
						$Cache_result = $SearchCacheModel->add($data);
					}
					//将搜索到的全部数据合并输出到页面
					$NewAllArray = array_merge_recursive($NewWeibo_array,$NewWeiboUser_array);
					$assign['status'] = '1';//有数据的时候返回状态1
					$assign['data'] = $NewAllArray;
					 $this->output($assign);
				}
				break;
			case 'weibo':
					/*先查询缓存表中*/
					$map['keyword'] = array("in",$keyword);
					//将匹配关键字的最新的缓存id查出并处理放入infoID中
					$CacheInfo_id = $SearchCacheModel->field('max(cache_id)')->where($map)->group('keyword')->select();
					//如果在缓存表中找到对应数据Cache_data
					if ($CacheInfo_id) {
						foreach ($CacheInfo_id as $key => $value) {
							$infoID[] = $value['max(cache_id)'];
						}
						//将最新的缓存数据全部查询
						$maps['cache_id'] = array("in",$infoID);
						$CacheInfo = $SearchCacheModel->where($maps)->select();
						//获取没有过期的搜索缓存存放$Cache_data
						foreach ($CacheInfo as $key => $value) {
							//如果没有在过期时间内的数据 就不处理关键字数组
							$time_c = (time()-$value['update_time']);
							if ($time_c < '3600 ') {
								$Cache_data[] = $value;
								//将缓存中可用的关键字剔除生成新的数组，去like查询
								foreach ($keyword as $k => $v) {
									if ($v == $value['keyword']) {
										unset($keyword[$k]);
									}
								}
							}
						}

						//如果有数据但是已经超过缓存期就不处理关键字数组
						if ($Cache_data) {
							$keyword = array_merge($keyword); //将排除后生成的关键字数组重新排序
							$keyword_num = sizeof($keyword); //获取到关键词的元素个数
							//将得到的数据反序列化
							foreach ($Cache_data as $key => &$value) {
								$value['data'] = unserialize($value['data']);
							}

							//取出需要的返回界面的数据
							foreach ($Cache_data as $key => &$value) {
								$Cache_INFO[]= $value['data'];
							}
							//将取出的数据降维 三维变二维
							foreach ($Cache_INFO as $key => $value) {
								foreach($value as $k=>$v){
									$newArr[] = $v;
								}
							}
							//$newArr 缓存表中得到数据处理之后需要返回页面的数据
							$newArr = array_unset_redo($newArr,"weibo_id");
						}
					}
					$keyword_num = sizeof($keyword); //获取到关键词的元素个数
					/*** step3-1 将关键词进行Like模糊查询***/
					for ($i=0; $i < $keyword_num; $i++) {
						//查询微博内容
						$where_Weibo['content'] = array('like','%'.$keyword[$i].'%');
						$weiboCon = $weiboModel->where($where_Weibo)->select();

						// foreach($weiboCon as $key => &$value){
						// 	$user_avatar = \User\Lib\ImiLib::getAvatarByUserId($value['user_id']);
						// 	$value['avatar'] = $user_avatar['avatar'];
						// }

						//将查询的结果放入数组中存放
						$weiboCon && $weiboArr[] = array(
							'OBkeyword' => $keyword[$i],
							'ResultSet' => $weiboCon,
						);
						/*** step3-1-1 将搜索关键字存入搜索记录表中 WeiboSearchStat***/
						$SearchStatModel = D("Weibo/WeiboSearchStat");
						$data['keyword'] = $keyword[$i];
						$data['create_time'] = time();
						$Stat_ruselt = $SearchStatModel->add($data);
					}

					if (!$weiboArr) {
						if ($newArr) {
							$assign['status'] = '1';//返回状态为1
							$assign['data'] = $newArr; //将缓存中的值返回页面中
						}else{
							$assign['status'] = '0'; //没有数据的时候返回状态0
						}
						$this->output($assign);
					} else {
						/*** step3-2 去除数组中的空元素***/
						$weiboArr = array_filter($weiboArr);

						/*** step3-3 去除数组中重复数据且不改变键值 ***/
						$NewWeibo_arr = array();//声明一个数组
						//$NewWeibo_arr 用于添加搜索缓存结果集
						foreach ($weiboArr as $key => $value) {
							foreach ($value['ResultSet'] as $k => $v) {
								$v['type'] = 'weibo';
								$v['OBkeyword'] = $value['OBkeyword'];
								$NewWeibo_arr[] = $v;
							}
						}

						//$NewWeibo_array 用户返回界面搜索结果
						foreach ($weiboArr as $key => $value) {
							foreach ($value['ResultSet'] as $k => $v) {
								$v['type'] = 'weibo';
								$NewWeibo_array[] = $v;
							}
						}

						//使用array_unique_fb方法去除数组中重复数据且不改变键值
						$NewWeibo_arr = array_unique_fb($NewWeibo_arr); //用于添加搜索缓存结果集
						$NewWeibo_array = array_unique_fb($NewWeibo_array); //用于返回界面结果集
						/*** step3-4 将关键之搜索到的数据集插入到缓存表中 WeiboSearchCache ***/
						/*** step3-4-1 将数组重新按关键字分组 ***/
						$SearchCacheModel = D("Weibo/WeiboSearchCache");
						$result_weibo = array();
						//将搜索关键词对应结果集序列化
						foreach ($NewWeibo_arr as $key => $value) {
							$result_weibo[$value['OBkeyword']][] = $value;
						}

						foreach ($result_weibo as $key => &$value) {
							foreach ($value as $k => &$v) {
								$user_avatar = \User\Lib\ImiLib::getAvatarByUserId($v['user_id']);
								$v['avatar'] = $user_avatar['avatar'];
							}
							$value = serialize($value);
							$data['keyword'] = $key;
							$data['data'] = $value;
							$data['type'] = '1'; //1微博 2微博用户
							$data['update_time'] = time();
							$Cache_result = $SearchCacheModel->add($data);

						}
						//EDIT BY 2017 2 21 H start  添加微博头像
						foreach ($NewWeibo_array as $key => &$value) {
							$user_avatar = \User\Lib\ImiLib::getAvatarByUserId($value['user_id']);
							$value['avatar'] = $user_avatar['avatar'];
						}
						//EDIT BY 2017 2 21 H end

						//如果有缓存数据，将缓存数据和查询到的数据合并
						if ($newArr) {
							//将缓存和查到的数据合并
							$NewWeibo_array = array_merge_recursive($newArr,$NewWeibo_array);
						}
						$assign['status'] = '1'; //有数据的时候返回状态1
						$assign['data'] = $NewWeibo_array;
						$this -> output($assign);
					}
				break;
			case 'user':
				//type是用户的时候需要获取当前用户的id

				/*先查询缓存表中*/
				$map['keyword'] = array("in",$keyword);
				//将匹配关键字的最新的缓存id查出并处理放入infoID中
				$CacheInfo_id = $SearchCacheModel->field('max(cache_id)')->where($map)->group('keyword')->select();
				//如果在缓存表中找到对应数据Cache_data
				if ($CacheInfo_id) {
					foreach ($CacheInfo_id as $key => $value) {
						$infoID[] = $value['max(cache_id)'];
					}
					//将最新的缓存数据全部查询
					$maps['cache_id'] = array("in",$infoID);
					$CacheInfo = $SearchCacheModel->where($maps)->select();

					//获取没有过期的搜索缓存存放$Cache_data
					foreach ($CacheInfo as $key => $value) {
						//如果没有在过期时间内的数据 就不处理关键字数组
						$time_c = (time()-$value['update_time']);
						if ($time_c < '360000') {
							$Cache_data[] = $value;
							//将缓存中可用的关键字剔除生成新的数组，去like查询
							foreach ($keyword as $k => $v) {
								if ($v == $value['keyword']) {
									unset($keyword[$k]);
								}
							}
						}
					}
					//如果有数据但是已经超过缓存期就不处理关键字数组
					if ($Cache_data) {
						$keyword = array_merge($keyword); //将排除后生成的关键字数组重新排序
						$keyword_num = sizeof($keyword); //获取到关键词的元素个数
						//将得到的数据反序列化
						foreach ($Cache_data as $key => &$value) {
							$value['data'] = unserialize($value['data']);
						}
						//取出需要的返回界面的数据
						foreach ($Cache_data as $key => &$value) {
							$Cache_INFO[]= $value['data'];
						}

						//将取出的数据降维 三维变二维
						foreach ($Cache_INFO as $key => $value) {
							foreach($value as $k=>$v){
								$newArr[] = $v;
							}
						}
						//$newArr 缓存表中得到数据处理之后需要返回页面的数据
						$newArr = array_unset_redo($newArr,"weibo_uid");
					}
				}
				/*** step3-1 将关键词进行Like模糊查询***/
				for ($i=0; $i < $keyword_num; $i++) {
					//查询微博用户
					$where_WeiboUser['nickname'] = array('like','%'.$keyword[$i].'%');
					$weiboUserCon = $weiboUserModel->where($where_WeiboUser)->select();

					//将查询的结果放入数组中存放
					$weiboUserCon && $weiboUserArr[] = array(
						'OBkeyword' => $keyword[$i],
						'ResultSet' => $weiboUserCon,
					);
					/*** step3-1-1 将搜索关键字存入搜索记录表中 WeiboSearchStat***/
					$SearchStatModel = D("Weibo/WeiboSearchStat");
					$data['keyword'] = $keyword[$i];
					$data['create_time'] = time();
					$Stat_ruselt = $SearchStatModel->add($data);
				}
				if (!$weiboUserArr) {
					if ($newArr) {
						$assign['status'] = '1';//返回状态为1
						$assign['data'] = $newArr; //将缓存中的值返回页面中
					}else{
						$assign['status'] = '0';//返回状态为0
					}
					 $this->output($assign);
				} else {
					/*** step3-2 去除数组中的空元素***/
					$weiboUserArr = array_filter($weiboUserArr);
					/*** step3-3 去除数组中重复数据且不改变键值 ***/
					//声明一个数组
					$NewWeiboUser_arr = array();
					//微博用户类型
					//$NewWeiboUser_arr 用于添加搜索缓存结果集
					foreach ($weiboUserArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibouser';
							$v['OBkeyword'] = $value['OBkeyword'];
							$NewWeiboUser_arr[] = $v;
						}
					}
					//$NewWeiboUser_array 用于返回界面搜索结果
					foreach ($weiboUserArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibouser';
							$NewWeiboUser_array[] = $v;
						}
					}

					//使用array_unique_fb方法去除数组中重复数据且不改变键值
					// $NewWeiboUser_arr = array_unique_fb($NewWeiboUser_arr); //用于添加搜索缓存结果集
					// $NewWeiboUser_array = array_unique_fb($NewWeiboUser_array); //用于返回界面结果集


					//将用户头像放入返回数组中
					foreach ($NewWeiboUser_arr as $key => &$value) {
						$useravatar = \User\Lib\ImiLib::getAvatarByUserId($value['user_id']);
						if ($useravatar['avatar']) {
							$value['avatar'] = $useravatar['avatar'];
						} else {
							$value['avatar'] = '';
						}
					}

					/*查询用户关系*/
//					$user_id = '10'; //模拟当前用户id\
//					$user_id = \User\Lib\ImiLib::getCurrentUserId();
					$user = session('user');
					$user_id = $user['id'];
//					$user_id = '14';
					$UserRelationArr = $UserRelationModel->where("user_id = $user_id")->select(); //查询当前用户的用户关系表
					//将模糊查询到的数据添加关系字段
					foreach ($NewWeiboUser_arr as $key => &$value) { //0已关注1互相关注2未关注
						if ($value['user_id'] == $UserRelationArr[$key]['follow']) {
							$value['mutual_sta'] = $UserRelationArr[$key]['mutual'];
						} else {
							$value['mutual_sta'] = '2';
						}
					}

					//$NewWeiboUser_array 用于返回界面搜索结果
					foreach ($weiboUserArr as $key => $value) {
						foreach ($value['ResultSet'] as $k => $v) {
							$v['type'] = 'weibouser';
							$NewWeiboUser_array[] = $v;
						}
					}

					//EDIT BY 2017 2 21
					//使用array_unique_fb方法去除数组中重复数据且不改变键值
					$NewWeiboUser_arr = array_unique_fb($NewWeiboUser_arr); //用于添加搜索缓存结果集
					$NewWeiboUser_array = array_unique_fb($NewWeiboUser_array); //用于返回界面结果集

					/*** step3-4 将关键之搜索到的数据集插入到缓存表中 WeiboSearchCache***/
					/*** step3-4-1 将关键之搜索到的数据集插入到缓存表中 WeiboSearchCache***/
					$SearchCacheModel = D("Weibo/WeiboSearchCache");
					$result_weibouser = array();
					//将搜索关键词对应结果集序列化
					foreach ($NewWeiboUser_arr as $key => $value) {
						$result_weibouser[$value['OBkeyword']][] = $value;
					}
					foreach ($result_weibouser as $key => &$value) {
						$value = serialize($value);
						$data['keyword'] = $key;
						$data['data'] = $value;
						$data['type'] = '2'; //1微博 2微博用户
						$data['update_time'] = time();
						$Cache_result = $SearchCacheModel->add($data);
					}
					/*查询用户关系*/
					$UserRelationArr = $UserRelationModel->where("user_id = $user_id")->select(); //查询当前用户的用户关系表
					//将模糊查询到的数据添加关系字段
					foreach ($NewWeiboUser_array as $key => &$value) { //0已关注1互相关注2未关注
						if ($value['user_id'] == $UserRelationArr[$key]['follow']) {
							$value['mutual_sta'] = $UserRelationArr[$key]['mutual'];
						} else {
							$value['mutual_sta'] = '2';
						}
					}

					//将用户头像放入返回数组中
					foreach ($NewWeiboUser_array as $key => &$value) {
						$useravatar = \User\Lib\ImiLib::getAvatarByUserId($value['user_id']);
						if ($useravatar['avatar']) {
							// $value['avatar'] ='http://'.$_SERVER['SERVER_NAME']."/data/upload/avatar/".$useravatar['avatar'];
							$value['avatar'] = $useravatar['avatar'];
						} else {
							$value['avatar'] = '';
						}
					}
					//如果有缓存数据，将缓存数据和查询到的数据合并
					if ($newArr) {
						//将缓存和查到的数据合并
						$NewWeiboUser_array = array_merge_recursive($newArr,$NewWeiboUser_array);
					}
					$assign['status'] = '1'; //有数据的时候返回状态1
					$assign['data'] = $NewWeiboUser_array;
					$this->output($assign);
				}
				break;
		}
	}

	/**
	 * 获取热搜榜
	 * @author	haofei	2016-12-23
	 * @param	string	$setion		时间区间 hour小时|day天|week周|month月
	 * @param	number	$num		几小时或几天或几周几个月
	 */
	public function hots($setion = 'day', $num = 1){

		$assign[] = '';
		 $this -> output($assign);
	}
}

